package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constants.Constants;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * RPC客户端：
 * 1. 发送请求
 * 2. 接受响应
 */
public class Client {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1. 建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);//需要提前开放端口号
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = factory.newConnection();
        //2. 建立信道  先声明队列，不然会报错
        Channel channel = connection.createChannel();
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);

        //3. 发送请求，使用内置交换机
        //设置请求的唯一标识correlationId
        String correlationId = UUID.randomUUID().toString();
        String msg = "hello rpc request...";
        //设置请求的相关属性
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .correlationId(correlationId)
                .build();

        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,props,msg.getBytes());

        //接收响应 使用阻塞队列来接收信息
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String respMsg = new String(body);
                System.out.println("接收到回调消息"+respMsg);
                if (correlationId.equals(properties.getCorrelationId())){
                    //如果校验一致，说明就是我们想要的响应
                    response.offer(respMsg);
                }
            }
        };

        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        String result = response.take();
        System.out.println("[RPC Client 响应结果]:"+result);



    }
}
